package algorithm.math;


/**
 * leetcode : https://leetcode.com/problems/add-binary/description/
 * Difficulty : Easy
 *
 * 二进制数相加
 * @Author Antony
 * @Since 2018/7/25 17:33
 */
public class AddBinary {

    public static void main(String[] args) {
        char[] c = new char[5];
        c[4] = 'a';
        c[3] = 'b';

        String a = "11";
        String b = "1";
        System.out.println(addBinary(a,b));
    }

    /**
     * beats 95.88% - 2ms
     * 加法思路一样
     */
    public static String addBinary(String a, String b) {
        int aSize = a.length();
        int bSize = b.length();
        int resSize = aSize > bSize ? aSize+1 : bSize+1;
        char[] res = new char[resSize];

        int plusFlag = 0;
        int aIdx = aSize-1;
        int bIdx = bSize-1;
        int resIdx = resSize-1;
        int tmp_a,tmp_b,tmp_res;
        while(aIdx >=0 || bIdx>=0){
            tmp_a = aIdx>=0 ? charToInt(a.charAt(aIdx)) : 0;
            tmp_b = bIdx>=0 ? charToInt(b.charAt(bIdx)) : 0;
            tmp_res = tmp_a + tmp_b + plusFlag;
            plusFlag = 0;
            if(tmp_res >=2){
                tmp_res -=2;
                plusFlag = 1;
            }
            res[resIdx] = intToChar(tmp_res);
            aIdx--;
            bIdx--;
            resIdx--;
        }
        if(plusFlag != 0) {
            res[resIdx] = intToChar(1);
            resIdx--;
        }
        StringBuilder bu = new StringBuilder();
        for(int i=resIdx+1; i<resSize; i++){
            bu.append(res[i]);
        }
        return bu.toString();
    }

    static int charToInt(char c){
        return c - '0';
    }
    static char intToChar(int i){
        return (char)(i+'0');
    }
}
